// vuex维护购物车数据
import { delSelectCartList, getCartList, updateCartList } from '@/api/cart'
import { Toast } from 'vant'

export default {
  namespaced: true,
  state () {
    return {
      cartList: [],
      cartTotal: 0
    }
  },
  actions: {
    async getCartListAction (context) {
      const { data } = await getCartList()
      // 补充商品选中状态
      data.list.forEach(item => {
        item.isChecked = true
      })
      context.commit('setCartData', data)
    },
    async changeCountAction (context, data) {
      const {
        goodsNum,
        goodsId,
        goodsSkuId
      } = data
      context.commit('changeProCount', { goodsNum, goodsId })
      await updateCartList(goodsId, goodsNum, goodsSkuId)
    },
    async delSelectAction (context) {
      const selectList = context.getters.checkedCart.map(item => item.id)
      await delSelectCartList(selectList)
      Toast('删除成功')
      context.dispatch('getCartListAction')
    }
  },
  mutations: {
    setCartData (state, data) {
      state.cartList = data.list
      state.cartTotal = data.cartTotal
    },
    isCheckedToggle (state, goodsId) {
      const changeId = state.cartList.find(item => item.goods_id === goodsId)
      changeId.isChecked = !changeId.isChecked
    },
    allCheckedToggle (state, flag) {
      state.cartList.forEach(item => {
        item.isChecked = flag
      })
    },
    changeProCount (state, { goodsNum, goodsId }) {
      state.cartList.find(item => item.goods_id === goodsId).goods_num = goodsNum
    }
  },
  getters: {
    checkedCart (state) {
      return state.cartList.filter(item => item.isChecked)
    },
    checkedCount (state, getters) {
      return getters.checkedCart.reduce((sum, item) => sum + item.goods_num, 0)
    },
    checkedPrice (state, getters) {
      return getters.checkedCart.reduce((sum, item) => sum + item.goods_num * item.goods.goods_price_min, 0).toFixed(2)
    },
    isAllChecked (state) {
      return state.cartList.every(item => item.isChecked)
    }
  }
}
